﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Xfs
{
	public sealed class XfsSession : XfsEntity
	{
		#region 自定义属性
		public XfsNetSocketComponent? NetSocket
		{
			get
			{
				return this.GetParent<XfsNetSocketComponent>();
			}
		}
		public bool IsServer
		{
			get
			{
				return this.NetSocket.IsServer;
			}
		}
		public XfsAsyncUserToken UserToken
		{
			get
			{
				if (this.GetComponent<XfsAsyncUserToken>() == null)
				{
					this.AddComponent<XfsAsyncUserToken>();
				}
				return this.GetComponent<XfsAsyncUserToken>();
			}
		}
		public XfsHeartComponent Heart
		{
			get
			{
				if (this.GetComponent<XfsHeartComponent>() == null)
				{
					this.AddComponent<XfsHeartComponent>();
				}
				return this.GetComponent<XfsHeartComponent>();
			}
		}
		public IPEndPoint? RemoteAddress
		{
			get
			{
				if (this.UserToken != null && this.UserToken.Socket != null && this.IsRunning == true)
				{
					return this.UserToken.Socket.RemoteEndPoint as IPEndPoint;
				}
				else
				{
					return null;
				}
			}
		}		
		public bool IsRunning { get; set; } = false;
		public bool IsOuter { get { return this.NetSocket.IsOuter; } }
		
		public bool IsClosed = false;
		public readonly Dictionary<int, Action<IXfsResponse>> requestCallback = new Dictionary<int, Action<IXfsResponse>>();
		#endregion

		#region Dispose
		public override void Dispose()
		{
			if (this.IsDisposed)
			{
				return;
			}

			base.Dispose();			

			this.Close();		
		}
		#endregion

	}
}
